from exts import db
from datetime import datetime
from sqlalchemy_serializer import SerializerMixin


class BoardModel(db.Model, SerializerMixin):
    serialize_only = ("id", "name", "priority", "create_time")
    __tablename__ = "board"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20), unique=True)
    priority = db.Column(db.Integer, default=1)
    create_time = db.Column(db.DateTime, default=datetime.now)


# 定义帖子模型类，继承自数据库模型和序列化混合类
class PostModel(db.Model, SerializerMixin):
    # 指定序列化时仅包含的字段
    serialize_only = ("id", "title", "content", "create_time", "board", "author")
    # 数据库表名
    __tablename__ = "post"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)
    board_id = db.Column(db.Integer, db.ForeignKey("board.id"))
    author_id = db.Column(db.String(100), db.ForeignKey("user.id"))

    # 定义与板块模型的关系
    board = db.relationship("BoardModel", backref=db.backref("posts"))
    # 定义与用户模型的关系
    author = db.relationship("UserModel", backref=db.backref("posts"))



# BannerModel类用于表示数据库中的横幅（Banner）模型
class BannerModel(db.Model, SerializerMixin):
    __tablename__ = 'banner'  # 数据库表名为'banner'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 唯一标识符，自增ID
    name = db.Column(db.String(255), nullable=False)  # 横幅名称，不可为空
    image_url = db.Column(db.String(255), nullable=False)  # 横幅图像URL，不可为空
    link_url = db.Column(db.String(255), nullable=False)  # 横幅链接URL，不可为空
    priority = db.Column(db.Integer, default=0)  # 显示优先级，默认为0
    create_time = db.Column(db.DateTime, default=datetime.now)  # 创建时间，默认为当前时间



# 评论模型类，继承自数据库模型和序列化混合类
class CommentModel(db.Model, SerializerMixin):
    __tablename__ = 'comment'  # 数据库表名
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 评论ID，主键，自增
    content = db.Column(db.Text, nullable=False)  # 评论内容，不能为空
    create_time = db.Column(db.DateTime, default=datetime.now)  # 创建时间，默认为当前时间
    post_id = db.Column(db.Integer, db.ForeignKey("post.id"))  # 外键，关联帖子ID
    author_id = db.Column(db.String(100), db.ForeignKey("user.id"), nullable=False)  # 外键，关联用户ID，不能为空

    post = db.relationship("PostModel", backref=db.backref('comments', order_by="CommentModel.create_time.desc()", cascade="delete, delete-orphan"))  # 关联帖子模型
    author = db.relationship("UserModel", backref='comments')  # 关联用户模型
